﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace PayloadTracker.APRS.Parsers
{
    class GPGSA : IParser
    {
        /*
        GPS DOP and active satellites 

        eg1. $GPGSA,A,3,,,,,,16,18,,22,24,,,3.6,2.1,2.2*3C
        eg2. $GPGSA,A,3,19,28,14,18,27,22,31,39,,,,,1.7,1.0,1.3*35
        eg3. $GPGSA,A,2,03,06,,,,13,,19,23,,,,2.8,2.6,*1D

        1    = Mode:
               M=Manual, forced to operate in 2D or 3D
               A=Automatic, 3D/2D
        2    = Mode:
               1=Fix not available
               2=2D
               3=3D
        3-14 = IDs of SVs used in position fix (null for unused fields)
        15   = PDOP
        16   = HDOP
        17   = VDOP
        $GPGSA,
         * A,
         * 2,
         * 03,
         * 06,
         * ,
         * ,
         * ,
         * 13,
         * ,
         * ,
         * ,
         * 25,
         * ,
         * ,
         * 3.4,
         * 3.2,
         * *1B
        */


        Double PDOP = 0;
        Double HDOP = 0;
        Double VDOP = 0;

        Double[] DOP;

        CultureInfo NmeaCultureInfo = CultureInfo.CurrentCulture;

        public override APRSBeacon Parse(string sentence)
        {
            //throw new NotImplementedException();
            return null;
        }

        public Double[] ParseDOP(string sentence)
        {
            if (!IsValidSentence(sentence))
                throw new Exception("Invalid Sentence");

            DOP = new Double[3];

            // Divide the sentence into words
            var Words = Tools.NMEAWords(sentence);
            // Update the DOP values
            try
            {
                if (Words[15] != "" && Words[15] != null)
                {
                    PDOP = double.Parse(Words[15], NmeaCultureInfo);
                }
                if (Words[16] != "" && Words[16] != null)
                {
                    HDOP = double.Parse(Words[16], NmeaCultureInfo);
                }
                if (Words[17] != "" && Words[17] != null)
                {
                    VDOP = double.Parse(Words[17], NmeaCultureInfo);
                }
            }
            catch (System.FormatException)
            {
                return null;
            }

            DOP[0] = PDOP;
            DOP[1] = HDOP;
            DOP[2] = VDOP;

            return DOP;
        }
        public override bool IsValidSentence(string sentence)
        {
            if (!sentence.StartsWith("$GPGSA"))
                return false;

            //Checksum
            int crc = Convert.ToByte(sentence[1]);
            for (int i = 2; i < sentence.Length - 3; i++)
                crc ^= Convert.ToByte(sentence[i]);

            return sentence.EndsWith("*" + crc.ToString("X2"));

        }
    }
}
